<!--
 * @Description: 
 * @Author: chenju
 * @Date: 2022-03-22 17:08:41
 * @LastEditors: qingyang
 * @LastEditTime: 2023-07-24 10:54:29
-->
<template>
  <CDialog
    :title="title"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    confirm-text="确定"
  >
    <el-form ref="formRef" :model="taskForm" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="组织名称" prop="organizationCode">
            <el-input
              v-model:value="taskForm.organizationName"
              disabled
              v-if="isEditTask"
            ></el-input>
            <GSelectOrganization
              v-model:value="taskForm.organizationCode"
              @change="handleChangeSelectOrganization"
              isCurrent
              :clearable="false"
              v-else
            ></GSelectOrganization>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业名称" required>
            <el-input v-model="taskForm.companyName" placeholder="选择组织后自动带出" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <p class="g-font-14n1b g-mt16 g-mb16">设定组织边界</p>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="盘查周期" prop="inventoryYear">
            <el-date-picker
              v-model="taskForm.inventoryYear"
              style="width: 100%"
              type="year"
              value-format="YYYY"
              placeholder="请选择"
              :disabled="isEditTask"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="填报层级" prop="boundaryType">
            <el-radio-group
              v-model="taskForm.boundaryType"
              :disabled="isEditTask"
              @change="changeRadio"
            >
              <el-radio
                label="CHILD_FILL"
                :disabled="!!(orgTreeData?.length && !orgTreeData[0].children)"
                >子级分发填报</el-radio
              >
              <el-radio label="SELF_FILL">本级汇总填报</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="组织边界" prop="organizationBoundary">
            <el-tree-select
              :check-strictly="taskForm.boundaryType == 'SELF_FILL'"
              v-model="taskForm.organizationBoundary"
              :data="orgTreeData"
              :multiple="taskForm.boundaryType == 'CHILD_FILL'"
              collapse-tags
              collapse-tags-tooltip
              :show-checkbox="taskForm.boundaryType == 'CHILD_FILL'"
              filterable
              default-expand-all
              :props="treeSelectProps"
              :placeholder="!taskForm.organizationCode ? '请先选择组织' : '请选择'"
              style="width: 100%"
              :disabled="!taskForm.organizationCode || isEditTask"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="补充说明">
            <el-input
              type="textarea"
              v-model="taskForm.additionRemark"
              placeholder="请输入"
              maxlength="255"
              show-word-limit
              resize="none"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'AddOrEditTaskDialog'
};
</script>
<script lang="ts" setup>
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import GSelectOrganization from '@/businessComponents/GSelectOrganization/index.vue';
import type { GSelectOrganizationOptionItem } from '@/businessComponents/GSelectOrganization/index.vue';
import { useMessage } from '@/hooks/useMessage';
import { rules } from './rules';
import type { PostTaskCreateParams } from '@/apis/eci/emissionAccounting/model/inventoryTaskModel';
import {
  getTaskInfo,
  postTaskEdit,
  postTaskCreate
} from '@/apis/eci/emissionAccounting/inventoryTask';
import { getOrganizationTreeByUser } from '@/apis/system/organization';
import { GetOrganizationTreeResult } from '@/apis/system/model/organizationModel';
import { isJSON } from '@/utils';
import { cloneDeep } from 'lodash';
import { isString } from '@/utils/is';
import { store } from '@/store';

interface SelectFillTypeDialogProps {
  visible: boolean;
  // 提交类型
  type: 'ADD' | 'EDIT';
  // 当前任务编号，编辑时必传
  taskNo?: string;
}
const props = withDefaults(defineProps<SelectFillTypeDialogProps>(), {
  visible: false,
  type: 'ADD'
});
const emit = defineEmits(['update:visible', 'refresh']);

const { createMessage } = useMessage();

const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (!visible) {
      // 关闭时清空数据
      handleClear();
    } else {
      // 打开时初始化新数据
      initVisible();
    }
  }
);
const title = computed(() => {
  return props.type === 'EDIT' ? '编辑核算任务' : '创建核算任务';
});
const isEditTask = computed(() => {
  return !!(props.type === 'EDIT');
});
const formRef = ref();
const loading = ref(false);
const orgTreeData = ref<GetOrganizationTreeResult[]>([]);
const treeSelectProps = {
  label: 'organizationName'
};
const isLeafOrganization = ref(false);
const sourceOrganizationTree = ref<GetOrganizationTreeResult[]>([]);
type IBoundaryType = 'SELF_FILL' | 'CHILD_FILL' | '';
const taskForm = reactive({
  inventoryYear: '',
  organizationCode: '',
  organizationName: '',
  companyName: '',
  additionRemark: '',
  boundaryType: 'CHILD_FILL' as IBoundaryType,
  organizationBoundary: [] as string[] | string
});

// 提交按钮
function handleConfirm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitTaskReq();
    }
  });
}

// 请求接口
async function submitTaskReq() {
  try {
    loading.value = true;
    const params: PostTaskCreateParams = {
      inventoryYear: taskForm.inventoryYear,
      organizationCode: taskForm.organizationCode,
      organizationName: taskForm.organizationName,
      additionRemark: taskForm.additionRemark,
      organizationBoundary: isString(taskForm.organizationBoundary)
        ? [taskForm.organizationBoundary]
        : taskForm.organizationBoundary,
      boundaryType: taskForm.boundaryType
    };
    if (isEditTask.value) {
      Object.assign(params, {
        taskNo: props.taskNo
      });
      await postTaskEdit(params);
    } else {
      await postTaskCreate(params);
    }
    createMessage.success(`${isEditTask.value ? '编辑' : '创建'}任务成功`);
    dialogVisible.value = false;
    loading.value = false;
    emit('refresh');
  } catch (error) {
    loading.value = false;
  }
}

// 关闭时清空数据
function handleClear() {
  loading.value = false;
  formRef.value?.resetFields();
  taskForm.inventoryYear = '';
  taskForm.companyName = '';
  taskForm.organizationName = '';
  taskForm.organizationCode = '';
  taskForm.additionRemark = '';
  taskForm.boundaryType = 'CHILD_FILL';
  taskForm.organizationBoundary = [];

  // 获取组织边界树additionRemark
  getOrgTreeByInventoryYearReq();
}
const changeRadio = (val: string) => {
  if (val == 'SELF_FILL') {
    taskForm.organizationBoundary = '';
  } else {
    taskForm.organizationBoundary = [];
  }
};

// 打开时初始化
async function initVisible() {
  if (props.type === 'EDIT' && props.taskNo) {
    try {
      const taskInfo = await getTaskInfo(props.taskNo);
      taskForm.inventoryYear = taskInfo.inventoryYear;
      if (taskInfo.organizationBoundary && isJSON(taskInfo.organizationBoundary)) {
        if (taskInfo.boundaryType == 'CHILD_FILL') {
          taskForm.organizationBoundary = JSON.parse(taskInfo.organizationBoundary);
        } else {
          // 本级的话是字符串格式
          taskForm.organizationBoundary = JSON.parse(taskInfo.organizationBoundary)[0];
        }
      } else {
        taskForm.organizationBoundary = [];
      }
      taskForm.companyName = taskInfo.companyName;
      taskForm.organizationName = taskInfo.organizationName;
      taskForm.organizationCode = taskInfo.organizationCode;
      taskForm.additionRemark = taskInfo.additionRemark;
      taskForm.boundaryType = taskInfo.boundaryType;

      // 获取组织边界树additionRemark
      getOrgTreeByInventoryYearReq();
    } catch (error) {
      console.log('error', error);
    }
  } else {
    handleClear();
  }
}

// 选择组织后 自动带出公司
function handleChangeSelectOrganization(value: string, option: GSelectOrganizationOptionItem) {
  console.log('handleChangeSelectOrganization', value, option);
  taskForm.companyName = option?.item.companyName || '';
  taskForm.organizationName = option?.label || '';
  // 获取实际组织边界树
  getRealOrganizationBoundaryTree();
}

// watch(
//   () => orgTreeData.value,
//   val => {
//     if (val && val.length && !val[0].children) {
//       taskForm.boundaryType = 'SELF_FILL';
//     } else {
//       taskForm.boundaryType = 'CHILD_FILL';
//     }
//   }
// );
/**
 * 获取组织边界树
 */
async function getOrgTreeByInventoryYearReq() {
  try {
    // const res = await getOrgTreeByInventoryYear(taskForm.inventoryYear);
    const userId = store.state.user.userInfo.userId;
    const res = await getOrganizationTreeByUser(userId);
    sourceOrganizationTree.value = res;
    getRealOrganizationBoundaryTree();
  } catch (error) {
    console.log('error', error);
    orgTreeData.value = [];
  }
}

// 盘查周期改变时，重新查询组织边界树，并清空已选组织边界
function handleInventoryChange() {
  orgTreeData.value = [];
  sourceOrganizationTree.value = [];
  if (!isEditTask.value) {
    taskForm.organizationBoundary = [];
  }
  if (taskForm.inventoryYear) {
    getOrgTreeByInventoryYearReq();
  }
}

/**
 * 获取实际组织边界树
 */
function getRealOrganizationBoundaryTree() {
  // 没有选择盘查周期
  // if (!taskForm.inventoryYear) {
  //   orgTreeData.value = [];
  //   return;
  // }
  // 清空已选的组织边界
  if (!isEditTask.value) {
    taskForm.organizationBoundary = [];
  }
  // 选中组织是否是叶子结点
  isLeafOrganization.value = false;
  // 获取组织边界树
  orgTreeData.value = handleGetTreeByOrgCode(
    cloneDeep(sourceOrganizationTree.value),
    taskForm.organizationCode
  );
  console.log('getRealOrganizationBoundaryTree', orgTreeData.value);
  /**
   * 处理组织边界树遍历
   * @param sourceTree
   * @param organizationCode
   */
  function handleGetTreeByOrgCode(
    sourceTree: GetOrganizationTreeResult[],
    organizationCode: string
  ) {
    let res: GetOrganizationTreeResult[] = [];
    for (let i = 0; i < sourceTree.length; i++) {
      const item = sourceTree[i];
      Object.assign(item, {
        value: item.organizationCode
      });
      if (item.organizationCode === organizationCode) {
        res = [item];
        // if (item.isLeaf) {
        //   isLeafOrganization.value = true;
        // }
      }
      if (item.children?.length) {
        const cldRes = handleGetTreeByOrgCode(item.children, organizationCode);
        if (cldRes?.length) {
          res = cldRes;
        }
      }
    }
    return res;
  }
}
</script>
